<?php
// -----------------------------------------------------
// Created by : php-cache
// -----------------------------------------------------
// User: tf <1096392101@qq.com>
// -----------------------------------------------------
declare (strict_types=1);

namespace Gao\Cache\handler;


use Gao\Cache\Drive;

class RedisHandler extends Drive
{
    /**
     * @var \Redis
     */
    private $redis;

    /**
     * 配置参数
     * @var array
     */
    protected $options = [
        'host'       => '127.0.0.1',
        'port'       => 6379,
        'password'   => '',
        'select'     => 0,
        'timeout'    => 0,
        'expire'     => 0,
        'persistent' => false,
        'prefix'     => '',
        'serialize'  => [],
    ];

    public function __construct()
    {
        $this->redis = new \Redis();
        $this->redis->connect($this->options['host'], $this->options['port']);
    }

    /**
     * 获取redis
     * @param string $key
     * @param null $default
     * @return int|mixed|string|null
     */
    public function get($key, $default = null)
    {
        $key = $this->getCacheKey($key);

        $val = $this->redis->get($key);

        if (false === $val || is_null($val)) {
            return $default;
        }

        return $this->unserialize($val);
    }

    /**
     * 设置缓存
     * @param string $key
     * @param mixed $value
     * @param null $ttl
     * @return bool
     */
    public function set($key, $value, $ttl = null): bool
    {
        $key = $this->getCacheKey($key);

        $val = $this->serialize($value);

        if ($ttl) {
            $this->redis->setex($key,$ttl,$val);
        }else {
            $this->redis->set($key,$val);
        }
        return true;
    }

    /**
     * 删除缓存
     * @param string $key
     * @return bool
     */
    public function delete($key): bool
    {
        $res = $this->redis->del($this->getCacheKey($key));

        return $res > 0;
    }

    /**
     * 清除缓存
     * @return bool
     */
    public function clear(): bool
    {
        $this->redis->flushDB();

        return true;
    }

    /**
     * 是否存在
     * @param string $key
     * @return bool
     */
    public function has($key): bool
    {
        return (bool)$this->redis->exists($this->getCacheKey($key));
    }
}